package com.cvtt.xmpp.utils;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class CacheControler {

	public static long cacheFileinterval = 1 * 24 * 60 * 60 * 1000 ; //一天

	//Modified by huah in 212-10-05
	/**
	 * 从网上获取用户头像是否过期，true表示已经过期，false表示尚未过期
	 * */
	public static boolean isUserAvatarExpired(long lastFileModifiedTime) {
		long nowTime = System.currentTimeMillis();
		return (nowTime - lastFileModifiedTime) > cacheFileinterval;
	}
	
	public static String readCacheName(String filePath) {
		String content = ""; //文件内容字符串    	//打开文件    	
		File file = new File(filePath);    	//如果path是传递过来的参数，可以做一个非目录的判断
		if (file.isDirectory()){
			return "";
		} else {
			try {
				InputStream instream = new FileInputStream(file);
				if (instream != null) {
					InputStreamReader inputreader = new InputStreamReader(instream);
					BufferedReader buffreader = new BufferedReader(inputreader);
					String line;
					while (( line = buffreader.readLine()) != null) {
						content += line;
					}
					instream.close();
				}
			} catch (java.io.FileNotFoundException e) { 
				return ""; 
			} catch (IOException e) {    	
				return ""; 
			}
		}
		
		return content;
	}


	public static byte[] readCacheInputStream(File f) {
		byte[] bytes = null;
		try {
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			BufferedInputStream in;
			in = new BufferedInputStream(new FileInputStream(f));
			byte[] temp = new byte[1024];
			int size = 0;
			while ((size = in.read(temp)) != -1) {
				baos.write(temp, 0, size);
			}
			in.close();
			bytes = baos.toByteArray();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return bytes;
	}

}
